using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FBroSharp.Lib;
using FBroSharp.Event;
using FBroSharp.DataType;
using FBroSharp.Value;
using FBroSharp.Const;
using FBroSharp.Callback;

namespace 文件上传助手
{
    /// <summary>
    /// 浏览器事件处理 - 文件上传助手专用
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private Form1 _form;

        public BrowserEvent(Form1 form)
        {
            _form = form;
        }

        /// <summary>
        /// 浏览器创建完成
        /// </summary>
        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            _form.UpdateStatus("浏览器已就绪，正在加载上传页面...");
            Console.WriteLine("✅ 浏览器创建成功");
        }

        /// <summary>
        /// 弹窗控制 - 在当前窗口打开链接
        /// </summary>
        public override bool OnBeforePopup(
            IFBroSharpBrowser browser, 
            IFBroSharpFrame frame, 
            string target_url, 
            string target_frame_name,
            FBroSharpWindowOpenDisposition target_disposition, 
            bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, 
            ref FBroSharpWindowsInfo windowInfo,
            ref FBroSharpBrowserSetting settings,
            ref bool no_javascript_access, 
            IFBroSharpUseExtraData user_settings)
        {
            // 在当前窗口打开
            frame.LoadURL(target_url);
            return true; // 阻止弹窗
        }

        /// <summary>
        /// URL 变化
        /// </summary>
        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                _form.UpdateUrl(url);
            }
        }

        /// <summary>
        /// 标题变化
        /// </summary>
        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            _form.UpdateTitle(title);
        }

        /// <summary>
        /// 加载状态变化
        /// </summary>
        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (!isLoading)
            {
                _form.UpdateStatus("页面加载完成");
                _form.OnPageLoadComplete();
            }
            else
            {
                _form.UpdateStatus("正在加载...");
            }
        }

        /// <summary>
        /// 页面加载完成
        /// </summary>
        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"页面加载完成 (HTTP {httpStatusCode})");
                Console.WriteLine($"✅ 页面加载完成: HTTP {httpStatusCode}");
            }
        }

        /// <summary>
        /// 页面加载错误
        /// </summary>
        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载失败: {errorText}");
                Console.WriteLine($"❌ 页面加载失败: {errorText} (代码: {errorCode})");
            }
        }

        /// <summary>
        /// 浏览器即将关闭
        /// </summary>
        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            Console.WriteLine("✅ 浏览器正在关闭");
        }

        /// <summary>
        /// 是否允许关闭
        /// </summary>
        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false 表示允许关闭
        }

        /// <summary>
        /// 文件对话框事件 - 拦截文件选择对话框实现自动上传
        /// </summary>
        public override bool OnFileDialog(
            IFBroSharpBrowser browser,
            FBroSharpFileDialogModeType mode,
            string title,
            string default_file_path,
            out List<string> accept_filters,
            IFBroSharpFileDialogEventCallback callback)
        {
            accept_filters = new List<string>();
            accept_filters.Add("所有文件 (*.*)|*.*");

            // 检查是否处于自动上传模式
            List<string> filesToUpload = GlobalUploadManager.GetFilesToUpload();

            if (filesToUpload != null && filesToUpload.Count > 0)
            {
                // 自动模式：直接返回文件列表，拦截对话框
                Console.WriteLine($"✅ OnFileDialog 拦截成功，自动上传文件: {filesToUpload[0]}");
                callback.Continue(filesToUpload);
                return true;  // 返回 true 表示拦截对话框，不显示系统对话框
            }
            else
            {
                // 手动模式：显示系统对话框
                Console.WriteLine("ℹ️ OnFileDialog 未启用自动上传，显示系统对话框");
                callback.Dispose();
                return false;  // 返回 false 表示显示系统对话框
            }
        }
    }
}

